package com.seeTools.next.conf;

import cn.dev33.satoken.exception.NotLoginException;
import com.seeTools.next.common.core.Result;
import com.seeTools.next.common.core.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author xiaotong
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验失败异常
     *
     * @param exception 异常类
     * @return 响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        String errMsg = bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(";"));
        log.info("@methodArgumentNotValidExceptionHandler#msg={}", errMsg);
        return Result.error(errMsg);
    }

    /**
     * 通用异常处理
     *
     * @param exception 异常类
     * @return 响应
     */
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception exception) {
        log.error("@exceptionHandler#msg={}", exception.getMessage(), exception);
        return Result.error("系统异常,请联系管理员");
    }

    /**
     * 未登录异常处理
     *
     * @param exception 异常类
     * @return 响应
     */
    @ExceptionHandler(NotLoginException.class)
    public Result<String> notLoginExceptionHandler(NotLoginException exception) {
        log.warn("@notLoginExceptionHandler#msg={}", exception.getMessage());
        return Result.error("您当前处于未登录状态");
    }

    /**
     * 服务异常处理
     *
     * @param exception 异常类
     * @return 响应
     */
    @ExceptionHandler(ServiceException.class)
    public Result<String> serviceExceptionHandler(ServiceException exception) {
        log.warn("@serviceExceptionHandler#msg={}", exception.getMessage());
        return Result.error(exception.getMessage());
    }
}
